package com.tj.api.rest.account;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.tj.api.annotations.SignIgnore;
import com.tj.api.annotations.VisitorAccessible;
import com.tj.api.rest.account.requset.BindWithDrawAccountRequest;
import com.tj.api.rest.account.requset.WithDrawPayoutNotifyRequest;
import com.tj.api.rest.account.requset.WithdrawRequest;
import com.tj.api.rest.account.response.BindWithDrawAccountResponse;
import com.tj.api.rest.account.response.WithdrawPageResponse;
import com.tj.api.rest.account.response.WithdrawProgressResponse;
import com.tj.api.rest.account.response.WithdrawRecordResponse;
import com.tj.bo.account.client.AccountQueryService;
import com.tj.bo.account.client.WithdrawService;
import com.tj.bo.account.client.vo.*;
import com.tj.bo.common.conf.api.ApiResponse;
import com.tj.bo.common.conf.config.RedisConfigUtil;
import com.tj.bo.common.conf.enums.RestCodeEnum;
import com.tj.bo.common.conf.util.PrivacyDimmerUtil;
import com.tj.template.config.vo.RequestLocalInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: anonymous
 * Date: 2020/06/11
 * Time: 下午2:16
 */
@RestController
@RequestMapping("/withdraw")
public class WithdrawController {
    private static final Logger logger = LoggerFactory.getLogger(WithdrawController.class);
    @Autowired
    private AccountQueryService accountQueryService;
    @Autowired
    private RedisConfigUtil accountConfig;
    @Autowired
    private WithdrawService withdrawService;

    /**
     * 提现页面
     *
     * @return
     */
    @RequestMapping("/page")
    public ApiResponse<WithdrawPageResponse> withdrawPage() {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        WithDrawAccountVO withDrawAccountVO = withdrawService.queryWithDrawAccount(userCode);
        AccountVO accountInfo = accountQueryService.getAccountInfo(userCode);

        WithdrawPageResponse withdrawPageResponse = new WithdrawPageResponse();
        withdrawPageResponse.setAadhaarFront(withDrawAccountVO.getAadhaarFront());
        withdrawPageResponse.setCanWithdrawalAmount("PKR" + accountInfo.getCanWithdrawalAmount());
        withdrawPageResponse.setAccount(PrivacyDimmerUtil.maskBankCard(withDrawAccountVO.getBankAccountNo()));
        withdrawPageResponse.setMinWithdrawalAmount(accountConfig.getMinWithdrawalAmount());
        withdrawPageResponse.setMaxWithdrawalAmount(accountConfig.getMaxWithdrawalAmount());
        withdrawPageResponse.setTips(accountConfig.getWithdrawPageTips());
        //withdrawPageResponse.setMobile(withDrawAccountVO.getUserMobile());
        withdrawPageResponse.setEmail(withDrawAccountVO.getUserEmail());
        return new ApiResponse<>(withdrawPageResponse);
    }

    /**
     * 绑定提现账号
     *
     * @param request
     * @return
     */
    @ParamsValidate
    @RequestMapping("/bind/account")
    public ApiResponse bindWithDrawAccount(@RequestBody BindWithDrawAccountRequest request) {
        request.verify();
        String bankName = withdrawService.getBankName(request.getIfsc());
        if (StringUtils.isEmpty(bankName)) {
            throw new ApplicationException("Please enter the correct IFSC");
        }
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();

        WithDrawAccountVO withDrawAccountVO = new WithDrawAccountVO();
        withDrawAccountVO.setUserCode(userCode);
        withDrawAccountVO.setBankAccountNo(request.getAccountNo());
        withDrawAccountVO.setBankName(bankName);
        withDrawAccountVO.setUserName(request.getName());
        withDrawAccountVO.setIfscCode(request.getIfsc());
        withDrawAccountVO.setUserEmail(request.getEmail());
        withdrawService.bindWithDrawAccount(withDrawAccountVO);
        return new ApiResponse();
    }

    /**
     * 查询提现账号
     *
     * @return
     */
    @RequestMapping("/get/bind/account")
    public ApiResponse<BindWithDrawAccountResponse> getBindAccount() {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        WithDrawAccountVO withDrawAccountVO = withdrawService.queryWithDrawAccount(userCode);
        BindWithDrawAccountResponse bindWithDrawAccountResponse = new BindWithDrawAccountResponse();
        bindWithDrawAccountResponse.setAccountNo(withDrawAccountVO.getBankAccountNo());
        bindWithDrawAccountResponse.setName(withDrawAccountVO.getUserName());
        bindWithDrawAccountResponse.setIfsc(withDrawAccountVO.getIfscCode());
        bindWithDrawAccountResponse.setEmail(withDrawAccountVO.getUserEmail());
        bindWithDrawAccountResponse.setModifyAllow(1);
        return new ApiResponse<>(bindWithDrawAccountResponse);
    }

    /**
     * 提现
     *
     * @param withdrawRequest
     * @return
     */
    @RequestMapping("")
    public ApiResponse withdraw(@RequestBody WithdrawRequest withdrawRequest) {
//        if (!accountConfig.getOpenWithdrawal()) {
//            logger.warn("提现功能暂时无法使用,withdrawRequest:{}", JSON.toJSONString(withdrawRequest));
//            throw new ApplicationException(RestCodeEnum.PARAM_RESOLVE_ERROR);
//        }

        withdrawRequest.verify();
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        AccountVO accountInfo = accountQueryService.getAccountInfo(userCode);
        if (accountInfo.getCanWithdrawalAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ApplicationException("Sorry, The amount that can be withdrawn is 0 rupee.");
        }
        WithDrawVO withDrawVO = new WithDrawVO();
        withDrawVO.setUserCode(userCode);
        withDrawVO.setAmount(withdrawRequest.getWithdrawAmount());
        withDrawVO.setUserMobile(withdrawRequest.getMobile());
        withdrawService.withDraw(withDrawVO);

        //提现自动审核 异步处理
        withdrawService.withDrawAutoAuditCheck(withDrawVO);
        return new ApiResponse();
    }

    /**
     * 提现结果异步回调
     */
    //@RequestMapping("/payout/notify")
    @VisitorAccessible
    @SignIgnore
    public ApiResponse withDrawPayoutNotify(@RequestBody WithDrawPayoutNotifyRequest withDrawPayoutNotifyRequest) {
        logger.info("提现结果异步回调:withDrawNotifyRequest:{}", JSON.toJSONString(withDrawPayoutNotifyRequest));
        WithDrawPayoutNotifyVO withDrawPayoutNotifyVO = new WithDrawPayoutNotifyVO();
        withDrawPayoutNotifyVO.setCode(withDrawPayoutNotifyRequest.getCode());
        withDrawPayoutNotifyVO.setMessage(withDrawPayoutNotifyRequest.getMessage());
        withDrawPayoutNotifyVO.setWithdrawOrderNo(withDrawPayoutNotifyRequest.getBizNo());
        withDrawPayoutNotifyVO.setAmount(new BigDecimal(withDrawPayoutNotifyRequest.getAcceptAmount()));
        withDrawPayoutNotifyVO.setPayAcceptNo(withDrawPayoutNotifyRequest.getAcceptNo());
        withDrawPayoutNotifyVO.setPaymentChannelName(withDrawPayoutNotifyRequest.getPaymentChannelName());
        withdrawService.withDrawPayoutNotify(withDrawPayoutNotifyVO);
        return new ApiResponse();
    }

    /**
     * 获取提现进度
     *
     * @return
     */
    @RequestMapping("/progress")
    public ApiResponse<WithdrawProgressResponse> getWithdrawProgress() {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        WithdrawRecordVO withdrawRecordVO = withdrawService.queryWithDrawProgress(userCode);
        return new ApiResponse<>(new WithdrawProgressResponse(withdrawRecordVO, accountConfig.getFaqStr(), accountConfig.getFaqMoreUrl()));
    }

    /**
     * 获取提现记录
     *
     * @return
     */
    @RequestMapping("/record")
    public ApiResponse<WithdrawRecordResponse> withdrawRecord() {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        List<WithdrawRecordVO> withdrawRecordList = withdrawService.getWithdrawRecordList(userCode);
        return new ApiResponse<>(new WithdrawRecordResponse(withdrawRecordList));
    }

    public static void main(String[] args) {
        String str = "20200731124752977397WD004350,202007311302125b5174WD000039";
        String[] strArr = str.split(",");
        for (String s : strArr) {
            if (StringUtils.isEmpty(s)) {
                continue;
            }
            Map<String, String> head = new HashMap<>();
            head.put("Content-Type", "application/json");
            JSONObject body = JSON.parseObject("{\n" +
                    "    \"code\":\"0000\",\n" +
                    "    \"message\":\"success\",\n" +
                    "    \"bizNo\":\"202007311042525b5653WD003756\",\n" +
                    "    \"acceptAmount\":\"1\",\n" +
                    "    \"acceptNo\":\"20200803manual06\",\n" +
                    "    \"paymentChannelName\":\"-2\"\n" +
                    "}\n");
            body.put("bizNo", s);
            body.put("acceptNo", UUID.randomUUID().toString().replaceAll("-", ""));
            String rest = HttpUtil.postPageBody("https://app-api.abctradeapp.com/withdraw/payout/notify", head, body.toJSONString());
            System.out.println("----" + body.toJSONString() + "----------" + rest);
        }
    }
}